<!--添加产品组件-->
<template>
  <div>
    <el-dialog
      :title="title"
      :visible="visible"
      @close="cancelDialog"
      width="1200px"
      class="edit-form">
      <!-- 搜索模块 -->
      <SearchForm
        :show-collapse="!!searchFormColumns.slice(0, 2).length"
        :data="searchFormColumns"
        :compact-data="searchFormColumns.slice(0, 2)"
        @searchForm="searchForm"
        @resetForm="resetForm" />
      <!-- 列表模块 -->
      <el-editable
        ref="productTable"
        class="hospital-edit-box"
        v-loading="productLoading"
        :data="productList"
        height="300"
        :columns="tableColumns"
        @selection-change="handleSelectionChange"
      >
        <template
          v-if="registrationNumber"
          :slot="`default-${registrationNumber}`"
          slot-scope="scope">
          <el-button
            :disabled="!scope.row[registrationNumber]||!scope.row[registrationId]"
            v-html="regisNoButton(scope.row, [registrationNumber, registrationId])"
            @click="showPdfRegistion(scope.row[registrationId])"
            type="text"
          />
        </template>
      </el-editable>
      <!-- 分页模块 -->
      <el-pagination
        align="right"
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="curPage"
        :page-sizes="PAGE_NUMBER"
        :page-size="pageSize"
        :layout="PAGINATION_LAYOUT"
        :total="totalElements"
      />
      <div
        slot="footer"
        class="dialog-footer">
        <el-button @click="cancelDialog">取消</el-button>
        <el-button
          type="primary"
          @click="confirmDialog()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import SearchForm from '@components/businesscomponents/search'
import ElEditable from '@components/el-editable'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common'
import { regisNoButton, showPdfRegistion } from '@const/agencySaas'
import { cloneDeep } from 'lodash'

export default {
  name: 'AddProduct',
  components: {
    SearchForm, ElEditable
  },
  props: {
    // 多属性就用逗号隔开（,） 如： "id, key"
    keyIn: {
      type: String,
      default: ''
    },
    // 多属性就用逗号隔开（,） 如： "id, key"
    keyOut: {
      type: String,
      default: 'id'
    },
    title: {
      type: String,
      default: '选择产品'
    },
    visible: {
      type: Boolean,
      default: false
    },
    queryUrl: { // 产品列表查询url
      type: String,
      default: '#'
    },
    queryMethod: {
      type: String,
      default: 'post'
    },
    extraQuery: { // 要添加的额外请求参数
      type: Object,
      default: () => {}
    },
    addedProducts: { // 添加之前已选中的产品
      type: Array,
      default: () => []
    },
    isChecked: {
      type: Boolean,
      default: false
    },
    registrationId: {
      type: String,
      default: ''
    },
    registrationNumber: {
      type: String,
      default: ''
    },
    searchFormColumns: { // 传入搜索表头
      type: Array,
      default: () => []
    },
    tableColumns: { // 传入table表头
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      dialogShow: true,
      curPage: 1,
      PAGE_NUMBER,
      PAGINATION_LAYOUT,
      pageSize: PAGE_NUMBER[0],
      totalElements: 0,
      productList: [], // 添加采购产品弹窗中，根据筛选条件查询出的可以采购的产品列表
      searchQuery: {},
      productLoading: false,
      product: [],
      currentPageProducts: [], // 当前页选中产品
      currentProducts: [] // 当前选中产品
    }
  },
  computed: {
    keyInArr () {
      const arr = this.keyIn ? this.keyIn.replace(/\s/g, '').split(',') : this.keyOutArr
      return arr
    },
    keyOutArr () {
      const arr = this.keyOut.replace(/\s/g, '').split(',')
      return arr
    }
  },
  watch: {
    visible (visible) {
      // 初始化
      if (visible) {
        const addedProducts = cloneDeep(this.addedProducts)
        addedProducts.forEach(i => {
          this.keyInArr.forEach((key, index) => {
            i[key] = i[this.keyOutArr[index]]
          })
        })
        this.currentProducts = this.isChecked ? addedProducts : []
        this.curPage = 1
        this.pageSize = PAGE_NUMBER[0]
        this.getProductList()
      }
    }
  },
  methods: {
    regisNoButton,
    showPdfRegistion,
    forEachList (target, source, fn) {
      target.forEach(i => {
        source.forEach(j => fn(i, j))
      })
    },
    // 获取产品列表
    getProductList () {
      const postData = {
        ...this.extraQuery,
        ...this.searchQuery,
        page: this.curPage,
        pageSize: this.pageSize
      }
      const url = this.queryUrl
      const method = '$' + this.queryMethod
      this.productLoading = true
      this.$axios[method](url, postData)
        .then(res => {
          this.productList = res.payload.content
          this.totalElements = res.payload.totalElements
          this.setCurrentSelection()
        })
        .finally(() => {
          this.productLoading = false
        })
        .catch((err) => {
          console.log(err)
          this.productLoading = false
          this.productList = []
          this.totalElements = 0
        })
    },
    // 搜索
    searchForm (condition) {
      this.curPage = 1
      this.searchQuery = condition
      this.updateCurrentSelection()
      this.getProductList()
    },
    // 重置
    resetForm (condition) {
      this.curPage = 1
      this.searchQuery = condition
      this.updateCurrentSelection()
      this.getProductList()
    },
    // 提交选择产品
    confirmDialog (isChecked = this.isChecked) {
      this.updateCurrentSelection()
      const products = isChecked ? this.currentProducts : this.currentPageProducts
      if (!products.length) {
        this.$message.warning('请选择产品')
        return
      }
      this.$emit('confirmDialog', products)
    },
    cancelDialog () {
      this.$emit('cancelDialog')
    },
    handleSizeChange (size) {
      this.pageSize = size
      this.updateCurrentSelection() // 换页就更新全部选中项数组
      this.getProductList()
    },
    handleCurrentChange (curPage) {
      this.curPage = curPage
      this.updateCurrentSelection()
      this.getProductList()
    },
    handleSelectionChange (selection) {
      this.currentPageProducts = selection
    },
    // 更新当前页选择项
    updateCurrentSelection (isChecked = this.isChecked) {
      if (!isChecked) {
        return void 0
      }
      const currentPageUpdateItems = []
      this.forEachList(this.productList, this.currentProducts, (i, j) => {
        let flag = this.keyInArr.every((key, index) => i[key] === j[key])
        if (flag) {
          currentPageUpdateItems.push(j)
        }
      })
      // 更新当前页选择项 先弃再取
      this.currentProducts = this.currentProducts.filter(item => !~currentPageUpdateItems.indexOf(item))
      this.currentProducts = this.currentProducts.concat(this.currentPageProducts)
    },
    // 已选择的产品打勾
    setCurrentSelection (isChecked = this.isChecked) {
      this.handleSelectionChange([])
      if (!isChecked) {
        return void 0
      }
      this.forEachList(this.productList, this.currentProducts, (i, j) => {
        let flag = this.keyInArr.every((key, index) => {
          return i[key] === j[key]
        })
        if (flag) {
          this.currentPageProducts.push(i)
          this.$nextTick(() => {
            this.$refs.productTable.$refs.table.toggleRowSelection(i, true)
          })
        }
      })
    }
  }
}
</script>
<style lang="less">

</style>
